;(function($) {

  RuS.Polar = function(elm, options) {

    var _RUS_POLAR = 'rus_polar';

    if (false === (this instanceof RuS.Polar)) {
      return new RuS.Polar(elm, options);
    }

    var defaultSettings = {
      width: 420,
      height: 420,
      border_width: 20,
      pd_t: 5, pd_r: 5, pd_b: 5, pd_l: 5,
      padding: 25,
      compass_radius: 30,
      anchorMode: false
    };

    var settings = $.extend(true, {}, defaultSettings, options);

    var _data = (function() {
      return {
        $el: elm,
        settings: settings,
        svg: createSvg(elm, settings)
      };
    })();

    var toggleAnchorMode = function() {
      settings.anchorMode = !settings.anchorMode;
      elm.select('svg').remove();
      _data.svg = createSvg(elm, settings);
    };

    // _data.svg.compass.click(function() {
    //   $('.toggle-compass').trigger('click');
    // });

    return {
      destroy: function() {
        elm.empty();
        return this;
      },

      update: function(data, colorArrow) {
        var svg = _data.svg;
        var cx = _data.settings.x + _data.settings.width / 2;
        var cy = _data.settings.y + _data.settings.height / 2;

        var bearing = data.Bearing;
        var compass = data.DfCompassCorrected / 10;

        if (_data.settings.anchorMode) {
          svg.dfArrow.animate({transform: 'r' + (bearing - compass) + ',' + cx + ',' + cy}, 0);

          svg.dfScale.animate({transform: 'r' + (-compass) + ',' + cx + ',' + cy}, 0);
          for (var i = 0, l = svg.dfScaleText.length; i < l; i += 1) {
            var text = svg.dfScaleText[i];
            var delta = 0;
            switch (i) {
              case 1:
                delta = 90;
                break;
              case 2:
                delta = 180;
                break;
              case 3:
                delta = 270;
                break;
            }
            text.animate({transform: 'r' + (-compass + delta) + ',' + cx + ',' + cy}, 0);
          }
        }
        else {
          svg.dfArrow.animate({transform: 'r' + bearing + ',' + cx + ',' + cy}, 0);
          svg.compass.animate({transform: 'r' + compass + ',' + cx + ',' + cy}, 0);
        }

        if (colorArrow) svg.dfArrow.attr('stroke', colorArrow);

        return this;
      },

      toggleCompass: toggleAnchorMode
    };
  };

  var createSvg = function(elm, settings) {
    var svg;

    if (elm instanceof d3.selection) {
      elm = elm[0][0];
    }
    else if (!elm.nodeType) {
      elm = elm[0];
    }

    var cx = settings.x + settings.width / 2;
    var cy = settings.y + settings.height / 2;
    var radius = settings.width / 2 - settings.padding;
    var innerRadius = radius - settings.border_width;
    var compassRadius = settings.compass_radius;

    svg = Raphael(elm, settings.x + settings.width, settings.y + settings.height);

    return {
      dfScale: dfScale(svg, cx, cy, compassRadius, radius, innerRadius),
      dfScaleText: dfScaleText(svg, cx, cy, compassRadius, radius, innerRadius),
      dfArrow: dfArrow(svg, cx, cy, compassRadius, radius),
      compass: compass(svg, cx, cy, compassRadius, settings)
    };
  };

  var dfScale = function(svg, cx, cy, compassRadius, radius, innerRadius) {
    var dirScale = svg.set();
    dirScale.push(svg.circle(cx, cy, radius).attr({"stroke-width": 1, "fill": "#2861b2", "stroke": "none"}));
    // dirScale.push(svg.circle(cx, cy, radius).attr({"stroke-width": 1, "fill": "#888888", "stroke": "none"}));
    [30, 60, 120, 150, 210, 240, 300, 330].forEach(function(i) {
      var winkelRad = i * (Math.PI / 180);
      var path_d = 'Mx0,y0Lx1,y1'
          .replace('x0', cx + Math.sin(winkelRad) * radius)
          .replace('y0', cy + Math.cos(winkelRad) * radius)
          .replace('x1', cx + Math.sin(winkelRad) * innerRadius)
          .replace('y1', cy + Math.cos(winkelRad) * innerRadius);
      dirScale.push(svg.path(path_d).attr({"stroke-width": 1, "stroke": "#FFFFFF", "fill": "none"}));
    });

    dirScale.push(svg.circle(cx, cy, innerRadius).attr({"stroke-width": 2, "fill": "#040506", "stroke": "#010202"}));
    for (var i = 0; i < 360; i += 90) {
      var winkelRad = i * (Math.PI / 180);
      var path_d = 'Mx0,y0Lx1,y1'
          .replace('x0', cx + Math.sin(winkelRad) * innerRadius)
          .replace('y0', cy + Math.cos(winkelRad) * innerRadius)
          .replace('x1', cx + Math.sin(winkelRad) * compassRadius)
          .replace('y1', cy + Math.cos(winkelRad) * compassRadius);
      dirScale.push(svg.path(path_d).attr({"stroke-width": 0.2, "stroke": "#FFFFFF", "fill": "none"}));
    }

    return dirScale;
  };

  var dfScaleText = function(svg, cx, cy, compassRadius, radius) {
    var texts = [];

    for (var i = 0; i < 360; i += 90) {
      var text;
      switch (i) {
        case 0:
          text = 'N';
          break;
        case 90:
          text = 'E';
          break;
        case 180:
          text = 'S';
          break;
        case 270:
          text = 'W';
          break;
        default :
          text = undefined;
      }

      if (text) {
        if (radius > 100) {
          texts.push(svg.text(cx, cy - radius + 10, text).attr({"font-size": 12, "stroke": "#FFFFFF", fill: '#FFFFFF', "text-anchor": 'middle'}).rotate(i, cx, cy, true));
        }
        else {
          texts.push(svg.text(cx, cy - radius + 10, text).attr({'stroke-width': 0.1, "font-size": 9, "stroke": "#FFFFFF", fill: '#FFFFFF', "text-anchor": 'middle'}).rotate(i, cx, cy, true));
        }
      } 
    }
    return texts;
  };

  var compass = function(svg, cx, cy, compassRadius, settings) {
    var compass = svg.set();
    var scale = 0.7

    var path_d = 'Mx0,y0Lx1,y1Hx2Lx0,y0'.replace(/x0/g, cx).replace(/y0/g, cy - 20 * scale).replace(/x1/g, cx - 8 * scale).replace(/y1/g, cy + 15 * scale).replace(/x2/g, cx + 8 * scale);
    compass.push(svg.path(path_d).attr({
      stroke: settings.anchorMode ? '#DDD' : "#FFF",
      "stroke-width": settings.anchorMode ? 2 : 1 * scale,
      fill: settings.anchorMode ? '#666' : 'none'
    }));

    return compass;
  };

  var dfArrow = function(svg, cx, cy, compassRadius, radius) {
    var path_d = 'Mx0,y0Lx0,y1'.replace(/x0/g, cx).replace('y0', cy - compassRadius).replace('y1', cy - radius);
    return svg.path(path_d).attr({"stroke-width": 4, "stroke": "none", "fill": "none"});
  };

  var rotateDfScale = function(angle) {
  };

})(jQuery);
